package com.android.ailaoshan.index.map;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.location.LocationManager;
import android.view.View;
import android.widget.Toast;

import com.android.ailaoshan.R;
import com.android.ailaoshan.common.BaseApplication;
import com.android.ailaoshan.common.ServiceIsRun;
import com.android.ailaoshan.location.LocationInfo;
import com.android.ailaoshan.location.LocationService;

import com.esri.arcgisruntime.geometry.PointCollection;
import com.esri.arcgisruntime.geometry.Polyline;
import com.esri.arcgisruntime.geometry.SpatialReferences;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.LineSymbol;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import org.litepal.LitePal;

import java.util.List;

public class MapPath {

    private View mapFragment;
    private MapView mMapView;
    private Context mContext;

    private PointCollection pointCollection;
    private GraphicsOverlay graphicsOverlay;
    private LineSymbol lineSymbol;

    private boolean isServiceRun;
    private boolean firstReceive = true;

    private FloatingActionButton recordPath;
    private FloatingActionButton recordEnd;

    private LocationChangeReceiver locationChangeReceiver;


    public MapPath(View view, MapView mapView) {
        this.mapFragment = view;
        this.mMapView = mapView;
        this.mContext = BaseApplication.getInstance().getbContext();
    }

    /**
     * 初始化
     */
    public void init(){
        // 查找控件
        recordEnd = mapFragment.findViewById(R.id.record_path_end);
        recordPath = mapFragment.findViewById(R.id.record_path_start);

        //初始化路径图层
        graphicsOverlay = new GraphicsOverlay();
        mMapView.getGraphicsOverlays().add(graphicsOverlay);
        this.pointCollection = new PointCollection(SpatialReferences.getWgs84());
        lineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.RED, 3.0f);

        buttonListener();
        pathIsRun();
    }



    /**
     * 判断记录轨迹是否运行
     */
    private void pathIsRun(){
        isServiceRun = ServiceIsRun.isServiceExisted(LocationService.class.getName());
        if(isServiceRun){
            recordPath.hide();
            recordEnd.show();

            // 注册广播接收器
            registerLocationChangeReceiver();
        }else{
            recordPath.show();
            recordEnd.hide();
        }
    }

    /**
     * 控件监听
     */
    private void buttonListener(){
        recordEnd.hide();
        recordPath.hide();

        recordPath.setOnClickListener(
            (v) -> {
                LocationManager locationManager = (LocationManager) mContext
                        .getSystemService(Context.LOCATION_SERVICE);
                if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
                    recordPath.hide();
                    recordEnd.show();
                    isServiceRun = true;
                    Intent intent = new Intent(mContext,LocationService.class);
                    mContext.startService(intent);

                    registerLocationChangeReceiver();
                }else{
                    Toast.makeText(mContext,"GPS开关没有打开，请打开开关后重试",Toast.LENGTH_SHORT).show();
                }
            }
        );
        recordEnd.setOnClickListener(
            (v) -> {
                recordEnd.hide();
                recordPath.show();
                isServiceRun = false;
                Intent intent = new Intent(mContext,LocationService.class);
                mContext.stopService(intent);

                unRegisterLocationChangeReceiver();
            }
        );
    }

    /**
     * 注册广播接收器
     */
    private void registerLocationChangeReceiver(){
        locationChangeReceiver = new LocationChangeReceiver();
        IntentFilter locationChangeFilter = new IntentFilter("android.ailaoshan.locationChangeReceiver");
        mContext.registerReceiver(locationChangeReceiver,locationChangeFilter);
    }


    /**
     * 注销广播
     */
    public void unRegisterLocationChangeReceiver(){
        if(locationChangeReceiver != null){
            mContext.unregisterReceiver(locationChangeReceiver);
        }
    }

    /**
     * 绘制路径
     */
    private void drawLocationLine(PointCollection pointCollection){
        Graphic graphic = new Graphic(new Polyline(pointCollection),lineSymbol);
        graphicsOverlay.getGraphics().add(graphic);
    }

    /**
     * 广播接收器
     */
    public class LocationChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            double lat = intent.getDoubleExtra("lat",0.0);
            double lng = intent.getDoubleExtra("lng",0.0);

            // 第一次接收到广播，从数据库中查询之前的点信息
            if(firstReceive){
                firstReceive = false;

                long time = intent.getLongExtra("infoNo",0);
                List<LocationInfo> locationInfoList = LitePal
                        .where("infoNo = ?",""+time).order("id")
                        .find(LocationInfo.class);

                if(locationInfoList.size() > 0){
                    for(LocationInfo locationInfo : locationInfoList){
                        pointCollection.add(locationInfo.getLng(),locationInfo.getLat());
                    }
                }
            }

            pointCollection.add(lng,lat);

            drawLocationLine(pointCollection);

            //阻止广播继续传递
            abortBroadcast();
        }
    }
}
